import { Component } from "react";
import { createPage, toast, base } from "nc-lightapp-front";
const { NCSelect, NCIcon, NCAffix } = base;

import WorkbenchDetail from "ssccommon/components/workbench-detail";
import pubMessage from 'ssccommon/utils/pubMessage';
import { initTemplate, listButtonClick, query } from "./events/index";
import presetVar from "./presetVar";
import requestApi from "./requestApi";
import { setSearch } from 'ssccommon/utils/setComponentUsed';

import "./index.less";

class AdjustRelationSearch extends Component {
  constructor(props) {
    super(props);
    setSearch(props, presetVar.searchArea)
    let multiLang = this.props.MutiInit.getIntl(2011);
    // 201103DJCX-0001":"缩略显示"
    this.state = {
      showType: "list",
      fuzzyquerychild: [],
      menuShowType: {
        type: "icon-Group",
        title: "缩略显示"
        // title:multiLang && multiLang.get('201103DJCX-0001')
      }
    };
    this.pubMessage = new pubMessage(props);
    // 查询条件
    this.queryKey = {
      fuzzyQueryKey: [],
      // 页信息
      pageinfo: {
        number: 1,
        size: 20,
        totalElements: 0,
        totalPages: 0
      },
      isfytzrelation: 'Y',
      queryKey: {}
    };
    // 缓存查询结果数据
    this.data = {
      listRows: [],
      cardRows: []
    };

    // 延时控制标记
    // 翻页
    this.canChangPageFlag = true;
    // 模糊查询
    this.fuzzyKey = "";

    // 页面初始化
    if (this.props.showRelationModal) {
      initTemplate.call(this, props);//点击关联按钮时才加载模板--ligru
    }
  }
  relateBill(ids) {
    let relatedata = {
      'transferinfo': ids,
      'tzdinfo': window.billinfo,
      'allrows': this.props.transferTable.getTransferTableValue(window.presetVar.list).rplist.outerData
    }
    requestApi.relation({
      data: relatedata,
      success: (data) => {
        window.closeRelation();
        window.removeEventListener("DOMMouseScroll",window.event);//火狐浏览器移除下滑监听
        window.onmousewheel = null;//其它浏览器移除下滑监听
        toast({ content: '关联成功', color: 'success' });
      },
      error: (data) => {

      }
    })
  }
  setTransferBtnDisabled(flag) {
    //设置“关联”按钮是否可用
    let btnObj = document.querySelector('.area-right .main-button');
    if (flag == true) {
      btnObj&&btnObj.setAttribute('disabled', true);
    } else {
      btnObj&&btnObj.removeAttribute('disabled');
    }

  }
  componentDidMount() {
    //设置“关联”按钮在不勾选任何数据的时候也可用 begin
    let that = this;
    var time = setInterval(() => {
      let btnObj = document.querySelector('.area-right .main-button');
      if (btnObj) {
        clearInterval(time);
        if (that.props.transferTable.getTransferTableValue(window.presetVar.list).rplist.outerData.length > 0) {
          btnObj.removeAttribute('disabled')
        }
        btnObj.addEventListener('click', function () {
          //判断是否有已选的条目，有就直接return， 无则继续执行逻辑
          let selectdata = that.props.transferTable.getTransferTableSelectedValue()
          if (selectdata != undefined && selectdata.rplist != undefined && selectdata.rplist.length > 0) {
            return;
          }
          that.relateBill(null);
        })
      }
    }, 300)
    //end
    // Firefox
    window.addEventListener("DOMMouseScroll", ev => {
      ev = ev || window.event;
      let onOff = null;
      if (ev.detail < 0) {
        onOff = true;
      } else {
        onOff = false;
      }
      let t = document.documentElement.scrollTop || document.body.scrollTop;
      let h =
        document.documentElement.scrollHeight || document.body.scrollHeight;
      let bh =
        document.documentElement.clientHeight || document.body.clientHeight;
      if (
        !onOff &&
        h - bh - t < 30 &&
        Number(this.queryKey.pageinfo.totalPages) > Number(this.queryKey.pageinfo.number) &&
        this.canChangPageFlag
      ) {
        this.canChangPageFlag = false;
        setTimeout(() => {
          query.queryData.call(this, true);
        }, 300);
      }
    });
    // 其他浏览器
    window.onmousewheel = ev => {
      ev = ev || window.event;
      let onOff = null;
      if (ev.wheelDelta > 0) {
        onOff = true;
      } else {
        onOff = false;
      }
      let t = document.documentElement.scrollTop || document.body.scrollTop;
      let h =
        document.documentElement.scrollHeight || document.body.scrollHeight;
      let bh =
        document.documentElement.clientHeight || document.body.clientHeight;
      if (
        !onOff &&
        h - bh - t < 30 &&
        Number(this.queryKey.pageinfo.totalPages) > Number(this.queryKey.pageinfo.number) &&
        this.canChangPageFlag
      ) {
        this.canChangPageFlag = false;
        setTimeout(() => {
          query.queryData.call(this, true);
        }, 300);
      }
    };
    this.props.transferTable.setTransferTableValue(window.presetVar.list, '', [], 'pk_bill', '');
  }
  menuClick = () => {
    // "201103DJCX-0001":"缩略显示",
    // "201103DJCX-0002":"列表显示",
    let multiLang = this.props.MutiInit.getIntl(2011);
    if (this.state.menuShowType.type == "icon-xingzhuang") {
      this.setState({
        menuShowType: {
          type: "icon-Group",
          title: multiLang && multiLang.get("201103TZGL-0001")
        },
        showType: "list"
      });
    } else {
      this.setState({
        menuShowType: {
          type: "icon-xingzhuang",
          title: multiLang && multiLang.get("201103TZGL-0002")
        },
        showType: "card"
      });
    }
  };
  // 模糊查询输入内容变化
  onFuzzyChange(data) {
    this.fuzzyKey = data;
    let newQueryKey = {};
    let multiLang = this.props.MutiInit.getIntl(2011);
    for (let child in this.queryKey) {
      newQueryKey[child] = this.queryKey[child];
    }
    newQueryKey.fuzzyQueryKey = data;
    setTimeout(
      (that, data) => {
        if (data == that.fuzzyKey) {
          requestApi.queryFuzzyKey({
            data: newQueryKey,
            success: data => {
              for (let childName in data.data) {
                data.data[childName].value =
                  data.data[childName].value + "=" + that.fuzzyKey;
                //201102BZCX-0049:包含
                data.data[childName].key =
                  data.data[childName].key + (multiLang && multiLang.get("201103TZGL-0003")) + that.fuzzyKey;
              }
              that.setState({ fuzzyquerychild: data.data });
            }
          });
        }
      },
      500,
      this,
      data
    );
  }
  // 模糊查询选择
  onFuzzySelected(data) {
    this.setState({ fuzzyquerychild: [] });
    // 更新查询条件
    this.queryKey.fuzzyQueryKey = data;
    // 查询数据
    query.queryData.call(this);
  }

  // 复制列表数据
  copyData(data) {
    let newData = {};
    newData.values = {};
    for (let child in data.values) {
      newData.values[child] = {
        value: data.values[child]&&data.values[child].value,
      };
      if(data.values[child]&&data.values[child].display) {
        newData.values[child].display = data.values[child].display
      }
      if(data.values[child]&&data.values[child].scale) {
        newData.values[child].scale = data.values[child].scale
      }
    }
    return newData;
  }
  searchClick(props, data, type) {
    this.queryKey.queryKey = data;

    query.queryData.call(this);
  }
  onRowDoubleClick = (values, idx, props, events) => {
    requestApi.openBill({
      data: {
        billtypeCode: values.billtypecode.value,
        transtypeCode: values.transtypecode.value,
        billid: values.busiid.value
      },
      success: data => {
        this.props.openTo(data.data.url, {
          ...data.data.data,
          scene: "fycx"
        });
      }
    });
  };

  render() {
    const { onRowDoubleClick } = this;
    const { table, search, transferTable } = this.props;
    const { createSimpleTable } = table;
    let { NCCreateSearch } = search;
    let { createTransferTable } = transferTable;
    let multiLang = this.props.MutiInit.getIntl(2011);
    let isShow = type => {
      if (this.state.showType == "list" && type == "list") {
        return "show";
      } else if (this.state.showType == "card" && type == "card") {
        return "show";
      } else {
        return "hide";
      }
    };
    let addMoreOnOff = this.data.listRows.length > 0 && this.queryKey.pageinfo.totalPages > this.queryKey.pageinfo.number
    return (
      <div id="rpBillList" className={addMoreOnOff ? 'add-more-wrap' : ''}>
        <div className="container">
          <NCAffix offsetTop={0}>
            <div className="title-box">
              <h1 className="ermbillsearch-title"></h1>
              <NCSelect
                className="fuzzyquery"
                tags
                supportSearch={true}
                searchPlaceholder={
                  multiLang && multiLang.get("201103TZGL-0004")
                }
                placeholder={multiLang && multiLang.get("201103TZGL-0005")}
                data={this.state.fuzzyquerychild}
                onSearch={this.onFuzzyChange.bind(this)}
                onChange={this.onFuzzySelected.bind(this)}
              />
              <i
                className={`menu-type-icon iconfont ${
                  this.state.menuShowType.type
                  }`}
                title={this.state.menuShowType.title}
                onClick={this.menuClick}
              />
            </div>
            <div className="ermbillsearch-header">
              {NCCreateSearch(
                presetVar.searchArea, //模块id
                {
                  clickSearchBtn: this.searchClick.bind(this), //   点击按钮事件
                  defaultConditionsNum: 1, //默认显示几个查询条件
                  showAdvBtn: false
                }
              )}
            </div>
          </NCAffix>
          <div className={isShow("list")} id="fytzrelation">
            {createTransferTable(
              {
                tableType: 'simple',
                editStatus: true,
                headTableId: window.presetVar.list,//表格组件id
                transferBtnText: multiLang&&multiLang.get('201102BCLF-0059'), //转单按钮显示文字
                cacheItem: ['busiid', 'billtypecode', 'billno', 'transtypecode', 'pk_bill'], //缓存字段
                containerSelector: '#fytzrelation', //容器的选择器 必须唯一,用于设置底部已选区域宽度
                afterEvent: (attrcode, value, record, index, oldvalue) => {/*编辑后事件*/ },
                onTransferBtnClick: (ids) => {//点击转单按钮钩子函数
                  this.relateBill(ids);
                },
                onCheckedChange: (flag, record, index, bodys) => { },
                onChangeViewClick: () => {/*点击切换视图钩子函数*/ },
                onCheckedChange: (flag, record, index, bodys) => {
                  this.setTransferBtnDisabled(false);
                }
              }
            )}
            {/* "201103DJCX-0008":"滑动加载更多" */}
            <div
              className='scroll-add-more'
              style={{ display: addMoreOnOff ? 'block' : 'none' }}
            >{multiLang && multiLang.get('201103TZGL-0006')}</div>
          </div>
          <div className={isShow("card")}>
            <WorkbenchDetail
              ref="detail"
              btns={this.state.btns}
              props={this.props}
              doAction={listButtonClick.bind(this)}
              getBtns={() => {
                if (this.queryKey.isComplate == "true") {
                  return ["Print", "Copy"];
                } else {
                  return ["Print", "Copy", "RemindingApproval"];
                }
              }}
            />
            <div
              className='scroll-add-more'
              style={{ display: addMoreOnOff ? 'block' : 'none' }}
            >{multiLang && multiLang.get('201103TZGL-0006')}</div>
          </div>
        </div>
      </div>
    );
  }
}
AdjustRelationSearch = createPage({
  mutiLangCode: "2011"
})(AdjustRelationSearch);
export default AdjustRelationSearch;
